home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: To malloc (new) or not to malloc? When is the question.
- Date: 10 Jan 1996 22:30:52 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4d1ems$hu7@news.iag.net>
- References: <4ctvk3$ort@maverick.tad.eds.com> <pwolf-0901960912510001@pwolf-mac.qualcomm.com>
- NNTP-Posting-Host: pm1-orl8.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <pwolf-0901960912510001@pwolf-mac.qualcomm.com>, pwolf@qualcomm.com
- says...
- ~
- ~In article <4ctvk3$ort@maverick.tad.eds.com>, fignet05.darrins@eds.com
- ~(Darrin Smith) wrote:
- ~[snip]
- ~~ Why is it that you can do something like the following:
- ~~ char *x;
- ~~ x="Some really long string with no particular meaning";
- ~~ and have no problems, but can't (safely) do something like this:
- ~~ struct st1{char one[10];
- ~~ char two[20];
- ~~ char three[10];
- ~~ };
- ~~ st1 *sptr; //or struct st1 *sptr in C instead of C++
- ~~ sptr=fread(....);
- <snip>
- ~~
- ~First example is incorrect. You may be thinking of declaring with
- initializing:
-
- What is wrong with the first example? "Some really long string with no
- particular meaning" is a string literal, which will be embedded in the exe
- somewhere. In an assignment expression, it decays to a pointer to its
- first element, like any char array. So x is assigned the address where
- this literal is embedded in the exe (simplified version, of course). The
- only problem might arise, if he attempts to write to it, since the literal
- can legally be stored as read-only.
-
- ~ char* x = "Some really long string with no particular meaning";
- ~
- ~Same thing works for second example if you initialize with constants:
- ~ struct st1{char one[10];
- ~ char two[20];
- ~ char three[10];
- ~ }* sptr= {0};
- ~
- ~The point is that memory allocatiion during initialization is required if
- ~you want the pointer to "automatically" point to memory which can be used.
- ~In your first example, the "x=" is NOT valid syntax for a sequence of
- ~characters. In your second example, memory for the structure was not
- ~allocated by your declaration of the pointer, so using the pointer for
- ~"fread()" puts information into unallocated memory.
-
- ?? This defines a pointer to struct st1, named sptr, and initializes it to
- NULL. Since a NULL pointer is guaranteed not to point to any valid object,
- this isn't going to work either. You will need to either malloc a struct
- or define one and set sptr to it.
-
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-